<template>
  <div class="mod-config">
    <div v-if="course">
      <div style="margin-bottom: 20px;">
        <el-button type="primary" @click="goback()">返回</el-button>
        <el-button type="primary" @click="showUpdate(bookId)">新增</el-button>
      </div>
      <el-table :data="dataList" border v-loading="dataListLoading" style="width: 100%;">
        <el-table-column prop="chapterName" header-align="center" align="center" label="课程名称"></el-table-column>
        <el-table-column header-align="center" align="center" label="课程封面">
          <template slot-scope="scope">
            <img :src="scope.row.courseCoverUrl" alt="">
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="课程视频封面">
          <template slot-scope="scope">
            <img :src="scope.row.sourceInfo?JSON.parse(scope.row.sourceInfo).cover_url:''" alt="">
          </template>
        </el-table-column>
        <el-table-column prop="courseVisit" header-align="center" align="center" label="播放量"></el-table-column>
        <el-table-column prop="courseLike" header-align="center" align="center" label="点赞数"></el-table-column>
        <el-table-column prop="courseFavorite" header-align="center" align="center" label="收藏量"></el-table-column>
        <el-table-column prop="qualifiedNum" header-align="center" align="center"
                         label="测试合格人数（uv）/人"></el-table-column>
        <el-table-column prop="unqualifiedNum" header-align="center" align="center"
                         label="测试不合格人数（uv）/人"></el-table-column>
        <el-table-column prop="participationTimes" header-align="center" align="center"
                         label="测试参与人数（pv）/人"></el-table-column>
        <el-table-column header-align="center" align="center" label="状态">
          <template slot-scope="scope">
            {{scope.row.isPublic==0?'未上架':'上架'}}
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="上架时间">
          <template slot-scope="scope">
            {{scope.row.publicTime=='2000-01-01 00:00:00'?'—':scope.row.publicTime}}
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="测试题" width="120">
          <template slot-scope="scope">
            <el-button v-if="scope.row.hasPaper == 0" type="text" size="small" @click="testAdd(bookId, scope.row.id)">
              新增
            </el-button>
            <div v-else>
              <el-button type="text" size="small" @click="testInfo(bookId, scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="testAdd(bookId, scope.row.id)">修改</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" width="150" label="操作">
          <template slot-scope="scope">
            <el-button style="color: #999;" v-if="scope.row.hasPaper === 0 " type="text" size="small" @click="tips">
              上架
            </el-button>
            <el-button v-if="scope.row.hasPaper !== 0 && scope.row.isPublic === 0" type="text" size="small" @click="courseUp(bookId, scope.row.id)">
              上架
            </el-button>
            <el-button type="text" size="small" @click="showInfo(bookId, scope.row.id)">查看</el-button>
            <el-button type="text" size="small" @click="showUpdate(bookId, scope.row.id)">修改</el-button>
            <el-button type="text" size="small" @click="delChannel(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </div>
    <test-question v-if="testAddVisiable" ref="testQuestion" @refresh='fromTest'></test-question>
    <test-question-info v-if="testInfoVisiable" ref="testQuestionInfo" @refresh='fromTest'></test-question-info>
    <audits-manage-add ref="auditsManageAdd" @refresh='getDataList'></audits-manage-add>
    <audits-manage-info ref="auditsManageInfo"></audits-manage-info>

    <el-dialog
      title="上架"
      :close-on-click-modal="false"
      :visible.sync="visible"
    >
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        label-width="150px"
      >
        <el-form-item
          label="上架时间"
          prop='isPublic'
          :rules="[
        {required: true, message: '请选择上架时间', trigger: 'change'},
        { validator: validatorPubilc, trigger: 'change' }
    ]"
        >
          <el-radio v-model="dataForm.isPublic" :label="1">立即上架</el-radio>
          <el-radio v-model="dataForm.isPublic" :label="0">定时上架</el-radio>
          <el-date-picker
            popper-class='dingTime'
            v-if="dataForm.isPublic === 0"
            v-model="dataForm.publicTime"
            type="datetime"
            placeholder="选择推送时间"
            style="margin-left: 20px;"
            @change="changeTime"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="getContent()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import AuditsManageAdd from "./update";
  import AuditsManageInfo from "./info";
  import testQuestion from "../testQuestion/update";
  import testQuestionInfo from "../testQuestion/info";

  export default {
    data() {
      return {
        visible: false,
        dataList: [],
        dataListLoading: false,
        dataForm: {
          isPublic: '',
          publicTime: ''
        },
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        course: true,
        testAddVisiable: false,
        testInfoVisiable: false,
        bookId: '',
        dataRule: {},
      };
    },
    components: {
      AuditsManageAdd, testQuestion, AuditsManageInfo, testQuestionInfo
    },
    mounted() {
    },
    methods: {
      validatorPubilc(rule, value, callback) {
        if (value === 0 && !this.dataForm.publicTime) {
          callback(new Error("请选择上架时间"));
        } else {
          callback();
        }
      },
      // 获取数据列表
      getDataList(id) {
        this.bookId = id
        this.dataListLoading = true;
        let obj = {
          page: this.pageIndex,
          limit: this.pageSize,
          bookId: id
        };
        this.$http({
          url: this.$http.adornUrl("/course/bookchapter/collegeCourseList"),
          method: "get",
          params: this.$http.adornParams(obj)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list;
            this.totalPage = data.page.totalCount;
          } else {
            this.dataList = [];
            this.totalPage = 0;
          }
          this.dataListLoading = false;
        });
      },
      tips() {
        this.$message.warning('请先新增测试题～')
      },
      delChannel(id) {
        this.$confirm('是否确认删除？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/course/bookchapter/deleteCollegeCourse'),
            method: 'post',
            data: id
          }).then(({data}) => {
            if (data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList(this.bookId)
                }
              });
            } else {
              this.$message.error(response.msg);
            }
          })
        }).catch(() => {

        })
      },
      changeTime() {
        if (new Date(this.dataForm.publicTime).getTime() < new Date().getTime()) {
          this.dataForm.publicTime = ''
          this.$message.error('所选时间要大于当前时间')
        }
      },
      courseUp(bookId, id) {
        this.dataForm.id = id
        this.dataForm.bookId = bookId
        this.visible = true
      },
      getContent() {
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(
                `/course/bookchapter/upChapter`
              ),
              method: "post",
              data: this.$http.adornData(this.dataForm)
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.getDataList(this.bookId);
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          }
        })
      },
      delTest(bookId, id) {
        this.$confirm('是否确认删除？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/college/collegecoursepaper/delete'),
            method: 'post',
            data: this.$http.adornData({bookId: bookId, chapterId: id})
          }).then(({data}) => {
            if (data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList(bookId)
                }
              });
            } else {
              this.$message.error(response.msg);
            }
          })
        }).catch(() => {

        })
      },
      testAdd(bookId, id) {
        this.course = false
        this.testAddVisiable = true
        this.$nextTick(() => {
          this.$refs.testQuestion.init(bookId, id);
        })
      },
      testInfo(bookId, id) {
        this.course = false
        this.testInfoVisiable = true
        this.$nextTick(() => {
          this.$refs.testQuestionInfo.init(bookId, id);
        })
      },
      fromTest(id) {
        this.course = true
        this.testAddVisiable = false
        this.testInfoVisiable = false
        this.getDataList(id)
      },
      showInfo(bookId, id) {
        this.$nextTick(() => {
          this.$refs.auditsManageInfo.init(bookId, id);
        })
      },
      showUpdate(bookId, id) {
        this.$nextTick(() => {
          this.$refs.auditsManageAdd.init(bookId, id);
        })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val;
        this.pageIndex = 1;
        this.getDataList(this.bookId);
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val;
        this.getDataList(this.bookId);
      },
      goback() {
        this.$emit('back')
      }
    }
  };
</script>
<style scoped>
  img {
    width: 50px;
    height: 50px;
  }
</style>
